package com.cxb.service;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

import com.cxb.GuardActivity;
import com.cxb.manager.PowerOffState;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.OperateSysDevicesUtils;
import com.cxb.utils.SharedPreferencesUtils;

public class CameraDayNightService extends Service {
	private int maxbrightness = 255;
	private final String NIGHT_MODE_NODE = "/sys/class/hm1375/night_mode/enable";
	private final String NIGHT_MODE_NODE_2 = "/sys/class/light/night_mode/night";//35SB
	private boolean preState;// ��һ��״̬
	private int checkCount = 0;
	private SharedPreferencesUtils spPreferencesUtils;

	public boolean isNightMode() {
		String node=NIGHT_MODE_NODE;
		if(!new File(NIGHT_MODE_NODE).exists()){
			node=NIGHT_MODE_NODE_2;
			maxbrightness = 110;
		}
		String enable = OperateSysDevicesUtils
				.native_readDataFormDeivce(node);
		return "1".equals(enable);

	}

	public void setNightMode(boolean enable) {
		// �ı�����ͷģʽ
		if(new File(NIGHT_MODE_NODE).exists()){
			OperateSysDevicesUtils.native_writeDataFromDevice(NIGHT_MODE_NODE,
					enable ? "1" : "0");
		}
		
		// �ı���Ļ����
		if (spPreferencesUtils != null && spPreferencesUtils.isAutoLight()) {
			if(PowerOffState.isPowerOffing){
				return;//关机页面不调节亮度  
			}
			Settings.System.putInt(getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE,
					Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
			Settings.System.putInt(getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS, enable ? 70 : maxbrightness);
			Intent intent = new Intent();
			intent.setAction("android.intent.action.setBrightness");
			this.sendBroadcast(intent);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		
		super.onCreate();
		if(!new File(NIGHT_MODE_NODE).exists()&&!new File(NIGHT_MODE_NODE_2).exists()){
			stopSelf();
			return;
		}
		Timer timer = new Timer();
		AdapterCameraLightTask adapterCameraLightTask = new AdapterCameraLightTask();
		timer.schedule(adapterCameraLightTask, 0, 1000);

		spPreferencesUtils = new SharedPreferencesUtils(this);
	}

	class AdapterCameraLightTask extends TimerTask {

		@Override
		public void run() {
			boolean isNight = isNightMode();
			if (isNight != preState) {
				preState = isNight;
			} else {
				checkCount++;
			}
//			Log.i("test", "camera current mode="+preState+" count="+checkCount);
			if (checkCount >= 5) {
				checkCount = 0;
				// �ı�����ͷģʽ����Ļ����
				setNightMode(preState);
			}

		}

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
}
